<template>
  <view class="w-[100%] h-[200rpx] flex py-3 items-center justify-center">
    <image
      :src="
        formData.avatar ||
        'https://youke1.picui.cn/s1/2025/09/23/68d213ce3793e.jpg'
      "
      mode="scaleToFill"
      class="w-[150rpx] h-[150rpx] rounded-full"
      @click="handleChooseAvatar"
    />
  </view>

  <view class="w-[98%] m-[auto] flex flex-col items-center justify-center">
    <view
      class="w-[90%] h-[auto] flex flex-col items-start justify-center p-2 text-f mb-2"
    >
      <text class="text-[30rpx] text-[#999]">姓名</text>
      <wd-input
        custom-class="ipt"
        placeholder="请输入姓名"
        v-model="formData.name"
      />
    </view>
    <view
      class="w-[90%] h-[auto] flex flex-col items-start justify-center p-2 text-f mb-2"
    >
      <text class="text-[30rpx] text-[#999]">电话</text>
      <wd-input
        custom-class="ipt"
        placeholder="请输入电话"
        v-model="formData.phone"
      />
    </view>
    <view
      class="w-[90%] h-[auto] flex flex-col items-start justify-center p-2 text-f mb-2"
    >
      <text class="text-[30rpx] text-[#999]">标识</text>
      <wd-picker
        custom-class="ipt"
        :columns="columns"
        v-model="formData.relation"
      />
    </view>
  </view>

  <view
    class="bg-gradient-to-r from-[#5669fd] to-[#5d98fc] w-[60%] h-[auto] m-auto flex items-center justify-center mt-10 text-f text-[#fff] p-4 rounded-[60rpx]"
    @click="handleSubmit"
  >
    提交
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { uploadImage } from '@/utils/upload'
import { addContact } from '@/api/contact'
import useStore from '@/store'

const user = useStore().useUser.getUser

interface FormData {
  name: string
  phone: string
  relation: string
  avatar: string
}

const formData = reactive<FormData>({
  name: '',
  phone: '',
  relation: '',
  avatar: ''
})

const handleChooseAvatar = async () => {
  const res = await uploadImage()
  formData.avatar = res
}

const columns = ref(['家人', '朋友', '其它'])

const handleSubmit = async () => {
  if (!formData.name || !formData.phone || !formData.relation) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  const res = await addContact<any, IContact>({
    user_id: user.id,
    name: formData.name,
    phone: formData.phone,
    relation: formData.relation,
    avatar: formData.avatar
  })
  if (res.code === 200) {
    uni.showToast({
      title: '提交成功',
      icon: 'success'
    })
  } else {
    uni.showToast({
      title: res.msg || '提交失败',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss">
.ipt {
  width: 100%;
  height: 70rpx;
  border-radius: 20rpx;
  padding: 8rpx;
  margin-top: 10rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
